<template>
    <div>
        <div v-show="false">{{ height }}{{ width }}{{ foreColor }}</div>
        <div class="view-chart" :id="detail.identifier" v-show="this.detail.dataBind.identifiers.length > 0" @dblclick="handleDblclick" />
        <div
            v-show="this.detail.dataBind.identifiers.length === 0"
            :style="{
                width: this.detail.style.position.w + 'px',
                height: this.detail.style.position.h + 'px',
                'text-align': 'center',
                'line-height': this.detail.style.position.h + 'px',
                'font-size': '30px',
                color: '#368a42',
            }"
            @dblclick="handleDblclick"
        >
            {{ $t('scada.topo.components.chart.view-chart.073848-0') }}
        </div>
        <el-dialog class="data-bind-dialog" :title="$t('scada.topo.components.chart.view-chart.073848-1')" :visible.sync="isVariableDia" width="600px" append-to-body>
            <div class="data-wrap" v-if="variableTree.length > 0">
                <div class="title-wrap">
                    <div class="left">{{ $t('scada.topo.components.chart.view-chart.073848-2') }}</div>
                    <div class="right"><i class="el-icon-refresh" @click="handleVariableRefresh"></i></div>
                </div>
                <div class="form-wrap">
                    <el-form label-position="top">
                        <el-form-item v-for="item in variableTree" :key="item.id" :label="item.name">
                            <el-checkbox-group v-model="checkList" style="margin-left: 10px">
                                <el-checkbox v-for="chil in item.children" :key="`${item.id}-${chil.id}`" :label="`${item.id}-${chil.id}`">{{ chil.name }}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <el-empty v-else :description="$t('scada.topo.components.chart.view-chart.073848-3')"></el-empty>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleConfirmClick">{{ $t('scada.topo.components.chart.view-chart.073848-4') }}</el-button>
                <el-button @click="isVariableDia = false">{{ $t('scada.topo.components.chart.view-chart.073848-5') }}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BaseView from '../View';
import topoUtil from '@/utils/topo/topo-util';
import { getListVariable, getListVariableHistory } from '@/api/scada/topo';

export default {
    name: 'viewChart',
    extends: BaseView,
    props: {},
    computed: {
        width() {
            this.$nextTick(function () {
                this.myChart.resize({
                    width: this.detail.style.position.w,
                    height: this.detail.style.position.h,
                });
            });
            return this.detail.style.position.w;
        },
        height() {
            this.$nextTick(function () {
                this.myChart.resize({
                    width: this.detail.style.position.w,
                    height: this.detail.style.position.h,
                });
            });
            return this.detail.style.position.h;
        },
        foreColor() {
            this.$nextTick(function () {
                this.option.legend.textStyle.color = this.detail.style.foreColor;
                this.setOption(this.option);
            });
            return this.detail.style.foreColor;
        },
    },
    data() {
        return {
            isVariableDia: false, // 变量对话框
            variableList: [], // 变量列表
            variableTree: [], // 变量树
            checkList: [], // 选中数据
            myChart: null,
            option: {
                title: {
                    text: '',
                },
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    align: 'right',
                    left: '3%',
                    top: '6%',
                    textStyle: { color: this.detail.style.foreColor },
                },
                grid: {
                    left: '6%',
                    right: '8%',
                    bottom: '6%',
                    containLabel: true,
                },
                xAxis: {
                    type: 'category',
                    data: [],
                    axisLabel: {
                        formatter: function (param) {
                            let time = param.split(' ')[1];
                            return time;
                        },
                        inside: false,
                    },
                    axisTick: {
                        alignWithLabel: true,
                    },
                },
                yAxis: {
                    type: 'value',
                },
                series: [],
                graphic: {
                    type: 'text', // 类型：文本
                    left: 'center',
                    top: 'middle',
                    silent: true, // 不响应事件
                    invisible: false, // 有数据就隐藏
                    style: {
                        fill: '#9d9d9d',
                        fontWeight: 'bold',
                        text: '暂无数据',
                        fontFamily: 'Microsoft YaHei',
                        fontSize: '25px',
                    },
                },
            },
            timer: null,
        };
    },
    async mounted() {
        this.myChart = this.$echarts.init(document.getElementById(this.detail.identifier));
        await this.getVariableList();
        const { identifiers } = this.detail.dataBind;
        if (!this.editMode && identifiers.length !== 0) {
            this.getChartsData();
            this.timer = setInterval(() => {
                this.getChartsData();
            }, 60000);
        } else {
            const ldata = ['XXX'];
            const xdata = ['2024:01:01 12:00:00', '2024:01:01 13:00:00'];
            const ydata = [{ name: 'XXX', data: [20, 30] }];
            this.setChartDatas(ldata, xdata, ydata);
            this.setOption(this.option);
        }
    },
    methods: {
        // 双击
        handleDblclick() {
            if (this.editMode) {
                this.isVariableDia = true;
            }
        },
        // 设备列表刷新
        handleVariableRefresh() {
            this.getVariableList();
        },
        //获取设备变量
        getVariableList() {
            return new Promise((resolve, reject) => {
                const { guid, type } = this.$route.query;
                const params = {
                    scadaGuid: guid,
                    type: type,
                    page: 1,
                    size: 9999,
                    ts: Date.parse(new Date()),
                };
                if (this.variableTree.length === 0) {
                    getListVariable(params).then((res) => {
                        resolve(res);
                        if (res.code == 200) {
                            this.variableList = res.rows;
                            this.variableTree = this.formatVariableTree(res.rows);
                        }
                    });
                }
            });
        },
        // 格式化属性数据
        formatVariableTree(list) {
            let datas = [];
            if (list.length !== 0) {
                list.forEach((item, i) => {
                    const type = Number(this.$route.query.type);
                    let serialNum = item.serialNumber;
                    let deviceNam = item.deviceName;
                    if (type === 1) {
                        deviceNam = item.productName;
                    }
                    if (type === 2) {
                        serialNum = item.sceneModelDeviceId;
                        deviceNam = item.sceneModelDeviceName;
                    }
                    if (i === 0) {
                        let par = {
                            id: serialNum,
                            name: deviceNam,
                            children: [
                                {
                                    id: item.identifier,
                                    name: item.modelName,
                                },
                            ],
                        };
                        datas.push(par);
                    } else {
                        const chil = {
                            id: item.identifier,
                            name: item.modelName,
                        };
                        if (type === 1) {
                            datas[0].children.push(chil);
                        } else {
                            const par = datas.find((d) => d.id === serialNum);
                            if (par) {
                                par.children.push(chil);
                            } else {
                                const par = {
                                    id: serialNum,
                                    name: deviceNam,
                                    children: [
                                        {
                                            id: item.identifier,
                                            name: item.modelName,
                                        },
                                    ],
                                };
                                datas.push(par);
                            }
                        }
                    }
                });
            }
            return datas;
        },
        // 确认数据
        handleConfirmClick() {
            if (this.checkList.length !== 0) {
                let id = this.checkList[0].split('-')[0];
                let res = this.checkList.find((item) => item.split('-')[0] !== id);
                if (res) {
                    this.$message.error(this.$t('scada.topo.components.chart.view-chart.073848-6'));
                    return;
                } else {
                    const type = Number(this.$route.query.type);
                    if (type === 1) {
                        this.detail.dataBind.serialNumber = '';
                    } else if (type === 2) {
                        this.detail.dataBind.sceneModelDeviceId = this.checkList[0].split('-')[0];
                    } else {
                        this.detail.dataBind.serialNumber = this.checkList[0].split('-')[0];
                    }
                    this.detail.dataBind.identifiers = this.checkList.map((item) => item.split('-')[1]);
                }
                this.$modal.msgSuccess(this.$t('scada.topo.components.chart.view-chart.073848-7'));
                // 例子
                const ldata = ['XXX'];
                const xdata = ['2024:01:01 12:00:00', '2024:01:01 13:00:00'];
                const ydata = [{ name: 'XXX', data: [20, 30] }];
                this.setChartDatas(ldata, xdata, ydata);
                this.setOption(this.option);
                this.isVariableDia = false;
            }
        },
        // 设置表格数据
        setChartDatas(ldata, xdata, ydata) {
            this.option.legend.data = ldata;
            this.option.xAxis.data = xdata;
            this.option.series = [];
            ydata.forEach((element) => {
                let data = {};
                if (this.detail.type == 'chart-line') {
                    data = {
                        name: element.name,
                        type: 'line',
                        stack: 'Total',
                        data: element.data,
                        itemStyle: {},
                    };
                } else if (this.detail.type == 'chart-line-step') {
                    data = {
                        name: element.name,
                        type: 'line',
                        stack: 'Total',
                        step: 'start',
                        data: element.data,
                        itemStyle: {},
                    };
                } else {
                    data = {
                        name: element.name,
                        type: 'bar',
                        stack: 'Total', //有代表是一个柱形图堆叠，无这属性柱形分散排列
                        barWidth: 17,
                        data: element.data,
                        itemStyle: {},
                    };
                }
                this.option.series.push(data);
            });
            this.option.graphic.invisible = ydata.length > 0;
        },
        setOption(option) {
            this.myChart.clear();
            this.myChart.setOption(option);
        },
        // 获取属性数据
        getChartsData() {
            const type = Number(this.$route.query.type);
            const { serialNumber, identifiers, sceneModelDeviceId } = this.detail.dataBind;
            const tempIdentifiers = identifiers.map((item) => {
                const obj = this.variableList.find((p) => p.identifier === item);
                return {
                    identifier: obj.identifier,
                    type: obj.type,
                };
            });
            let params = {
                scadaType: type,
                thingsModelList: tempIdentifiers,
                beginTime: topoUtil.getTime(8),
                endTime: topoUtil.getNowTime(),
                ts: Date.parse(new Date()) + Math.floor(Math.random() * 100),
            };
            if (type === 1) {
                if (!this.$route.query.serialNumber) {
                    return;
                } else {
                    params = { ...params, serialNumber: this.$route.query.serialNumber };
                }
            } else if (type === 2) {
                params = { ...params, sceneModelDeviceId: sceneModelDeviceId };
            } else {
                params = { ...params, serialNumber: serialNumber };
            }
            getListVariableHistory(params).then((res) => {
                if (res.code == 200) {
                    const modelIdens = Object.keys(res.data) || [];
                    if (modelIdens.length !== 0) {
                        const ldata = modelIdens.map((item) => this.variableList.find((p) => p.identifier === item).modelName);
                        const xdata = res.data[modelIdens[0]].map((item) => item.time);
                        const ydata = modelIdens.map((item) => ({
                            name: this.variableList.find((p) => p.identifier === item).modelName,
                            data: res.data[item].map((v) => v.value),
                        }));
                        this.setChartDatas(ldata, xdata, ydata);
                        this.setOption(this.option);
                    } else {
                        this.setChartDatas([], [], []);
                        this.setOption(this.option);
                    }
                }
            });
        },
    },
    beforeDestroy() {
        clearInterval(this.timer);
        this.timer = null;
    },
};
</script>

<style lang="scss" scoped>
.view-chart {
    height: 100%;
    width: 100%;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
}

.data-bind-dialog {
    .data-wrap {
        min-height: 400px;

        ::v-deep .el-form-item__label {
            padding: 0;
        }

        ::v-deep .el-form-item__content {
            margin-left: 14px;
        }

        .title-wrap {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            margin-bottom: 15px;

            .left {
                color: red;
            }

            .right {
                cursor: pointer;
            }
        }

        .form-wrap {
            height: 390px;
            overflow-y: auto;
        }
    }
}
</style>
